package com.sr.interceptor;

import com.sr.annotation.ApiAuth;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaochi
 * @date 2022/4/30 16:48
 * @desc GlobalInterceptor
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__)
public class GlobalInterceptor implements HandlerInterceptor {

    private final ApiAuthIntercptor apiAuthIntercptor;

    /**
     * 处理请求之前执行（Controller方法调用之前）
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果报错不能强转 HandlerMethod，是该路由没有排除，被拦截器拦截了，请排除路由就可以了
        HandlerMethod method = ((HandlerMethod) handler);
        boolean result;
        if (method.hasMethodAnnotation(ApiAuth.class)){
            result = apiAuthIntercptor.doHandler(request,response,method);
            if (!result){
                return result;
            }
        }
        return true;
    }
}
